package weiconsole;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import weibo4j.Timeline;
import weibo4j.model.Status;
import weibo4j.model.StatusWapper;
import weibo4j.model.WeiboException;
import weiconsole.ui.NativeUI;

public class TimelineManager {
	private static Timeline tm = new Timeline();
	private BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
	
	private List<Status> statuses = new ArrayList<Status>();
	
	public TimelineManager() {
		regModule();
	}
	
	public void regModule() {
		/* register user manager module */
		Module tmmod = new Module("weiconsole.TimelineManager", this);
		tmmod.addFunction("timeline");
		tmmod.addFunction("viewpic");
		Main.registerModule(tmmod);
	}
	
	private boolean checkStatuses() {
		if (statuses.isEmpty()) {
			Main.error("please fetch the timeline before doing this");
			return false;
		}
		return true;
	}
	
	private String getLine() {
		try {
			return stdin.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "";
	}
	
	public void timeline(String args[]) {
		if (!Main.checkLoggedIn()) return;
		
		StatusWapper statusWapper = null;
		try {
			statusWapper = tm.getFriendsTimeline();
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		
		statuses = statusWapper.getStatuses();
		displayStatuses(statuses);
	}
	
	public void viewpic(String args[]) {
		if (!checkStatuses()) return;
		
		if (args.length == 0) {
			Main.error("viewpic needs one parameter");
			return;
		}
		
		int index = Integer.parseInt(args[0]);
		
		String pic = statuses.get(index).getOriginalPic();
		if (pic.equals("")) {
			pic = statuses.get(index).getRetweetedStatus().getOriginalPic();
			if (pic.equals("")) {
				Main.error("no picture in selected status");
				return;
			}
		}
		openPic(pic);
	}
	
	public void timelineHelp() {
		System.out.println();
		System.out.println("press ENTER to display next status");
		System.out.println("n/next <count> - display next count statuses");
		System.out.println("s/stop - stop displaying statuses");
		System.out.println("repost - repost this status");
		System.out.println("comment - send comment");
		System.out.println("favorite - favorite this status");
		System.out.println("viewcomment - view comments");
		System.out.println("viewpic - view the picture");
	}
	
	public void displayStatuses(List<Status> statuses) {
		int index = 0;
		int skipCount = 0;
		for (Status status : statuses) {
			System.out.print("<" + index + ">");
			displayStatus(status);
			
			if (skipCount != 0) {
				index++;
				skipCount --;
				continue;
			}
			
			while (true) {
				System.out.print("press ENTER to continue> ");
				String cmd = getLine();
				
				if (cmd.equals("")) {
					System.out.println();
					break;
				}
				
				StringTokenizer st = new StringTokenizer(cmd);
				cmd = st.nextToken();
				
				int argc = st.countTokens();
				int i;
				String[] params = new String[argc];
				for (i = 0; i < argc; i++) {
					params[i] = st.nextToken();
				}
				
				if (cmd.equals("next") || cmd.equals("n")) {
					if (params.length < 1) break;
					skipCount = Integer.parseInt(params[0]) - 1;
					break;
				}
				if (cmd.equals("stop") || cmd.equals("s")) return;
				if (cmd.equals("help")) {
					timelineHelp();
					continue;
				} else if (cmd.equals("viewcomment")) {
					
				} else if (cmd.equals("viewpic")) {
					if (params.length == 0) {
						params = new String[1];
						params[0] = Integer.toString(index);
					}
					viewpic(params);
				} else {
					Main.error("unknown command: `" + cmd + "'");
					continue;
				}
			}
			index++;
		}
	}
	
	public void displayStatus(Status status) {
		Main.nativeUI.setForeground(NativeUI.CL_BLUE);
		System.out.print("@" + status.getUser().getName() + ": ");
		Main.nativeUI.setForeground(NativeUI.CL_NORMAL);
		
		String text = status.getText();
		boolean printingName = false;
		for (int i = 0; i < text.length(); i++) {
			if (printingName && ((text.charAt(i) == ' ') || (text.charAt(i) == ':'))) {
				printingName = false;
				Main.nativeUI.setForeground(NativeUI.CL_NORMAL);
			}
			if ((text.charAt(i) == '@') && (text.charAt(i + 1) != ' ')) {
				Main.nativeUI.setForeground(NativeUI.CL_BLUE);
				printingName = true;
			}
			System.out.print(text.charAt(i));
		}
		
		Main.nativeUI.setForeground(NativeUI.CL_NORMAL);
		String pic = status.getOriginalPic();
		if (!pic.equals("")) {
			System.out.println();
			System.out.print("picture: " + pic);
		}
		System.out.println();
		
		Status retweeted = status.getRetweetedStatus();
		if (null != retweeted) {
			System.out.print(">>> ");
			Main.nativeUI.setForeground(NativeUI.CL_BLUE);
			System.out.print("@" + retweeted.getUser().getName() + ": ");
			Main.nativeUI.setForeground(NativeUI.CL_GREEN);
			
			text = retweeted.getText();
			printingName = false;
			for (int i = 0; i < text.length(); i++) {
				if (printingName && ((text.charAt(i) == ' ') || (text.charAt(i) == ':'))) {
					printingName = false;
					Main.nativeUI.setForeground(NativeUI.CL_GREEN);
				}
				if ((text.charAt(i) == '@') && (text.charAt(i + 1) != ' ')) {
					Main.nativeUI.setForeground(NativeUI.CL_BLUE);
					printingName = true;
				}
				System.out.print(text.charAt(i));
			}
			Main.nativeUI.setForeground(NativeUI.CL_GREEN);
			pic = retweeted.getOriginalPic();
			if (!pic.equals("")) {
				System.out.println();
				System.out.print("picture: " + pic);
			}
			System.out.println();
			
			System.out.print(">>> " + Main.printDate(retweeted.getCreatedAt()));
			System.out.print(" via " + retweeted.getSource().getName());
			System.out.print(" Reposts: " + retweeted.getRepostsCount());
			System.out.print(" Comments: " + retweeted.getCommentsCount());
			if (retweeted.isFavorited()) {
				Main.nativeUI.setForeground(NativeUI.CL_RED);
				System.out.print(" Favorited");
			}
			Main.nativeUI.setForeground(NativeUI.CL_NORMAL);
			System.out.println();
		}
		
		System.out.print(Main.printDate(status.getCreatedAt()));
		System.out.print(" via " + status.getSource().getName());
		System.out.print(" Reposts: " + status.getRepostsCount());
		System.out.print(" Comments: " + status.getCommentsCount());
		if (status.isFavorited()) {
			Main.nativeUI.setForeground(NativeUI.CL_RED);
			System.out.print(" Favorited");
			Main.nativeUI.setForeground(NativeUI.CL_NORMAL);
		}
		System.out.println();
		System.out.println();
	}
	
	private void openPic(String pic) {
		System.out.println("opening " + pic + "...");
		if(java.awt.Desktop.isDesktopSupported()){
            try {
                java.net.URI uri = java.net.URI.create(pic); 
                java.awt.Desktop dp = java.awt.Desktop.getDesktop();
                if(dp.isSupported(java.awt.Desktop.Action.BROWSE)){
                    dp.browse(uri);    
                } else {
                	Main.error("system doesn't support java.awt.Desktop.Action.BROWSE");
                }
            } catch(java.lang.NullPointerException e){
            } catch (java.io.IOException e) {
            	Main.error("cannot find the default browser");
            }           
		} else {
			Main.error("system doesn't support java.awt.Desktop");
		}
	}
}
